<?php

require_once Yii::app()->getBasePath() . '/messages/Message.php';
require_once Yii::app()->getBasePath() . '/messages/MsgType.php';

class UsersController extends GxController {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('index', 'view'),
//                'users' => array('*'),
                'users' => array('@'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('create', 'update', 'password', 'profile', 'restaurant'),
                'users' => array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('admin', 'delete'),
                //  'users' => array('admin'),
                'users' => User::getAdmins(),
            // 'roles' => array('3'),
            //  'expression'=>'!$user->isGuest && Yii::app()->user->hasRole(WebUser::RESTURANTADMINROLID)==3',
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $this->render('view', array(
            'model' => $this->loadModel($id, 'Users'),
        ));
    }

    public function actionCreate() {
        $model = new Users;
        $profile = new Profiles();
        $selected = array();
        $this->performAjaxValidation(array($model, $profile));
        if (isset($_POST['Users'], $_POST['Profiles'])) {


            $model->setAttributes($_POST['Users']);
            $model->setAttribute('createtime', time());
            $model->setAttribute('lastvisit', time());
            $model->setAttribute('password', $model->getAttribute('password'));
            $profile = $profile->setProfile($_POST['Profiles']);
            $valid = $model->validate();
            $valid = $profile->validate() && $valid;

            if ($valid) {

                $transaction = $model->getDbConnection()->beginTransaction();
                try {

                    $model->setAttribute('password', md5($model->getAttribute('password')));

                    if ($model->save(false)) {
                        $profile->setAttribute('users_id', $model->id);
                        $profile->save(false);

                        $model->addUserRole($_POST['Users']['userRole']);

                        $transaction->commit();
                        $this->redirect(array('admin'));
                    }
                } catch (Exception $e) {
                    $transaction->rollback();
                    throw $e;
                }
            }
        }

        $this->render('create', array('model' => $model, 'profile' => $profile, 'selected' => $selected));
    }

    public function actionUpdate($id) {

        $profile = '';
        $model = $this->loadModel($id, 'Users');
        $profile = isset($model->profiles[0]) ? $model->profiles[0] : new Profiles();

        $selected = array();
        $this->performAjaxValidation(array($model, $profile));
        if (isset($_POST['Users'])) {
            if (isset($_POST['Users']['restaurantAdmins'])) {
                $selected = $_POST['Users']['restaurantAdmins'];
            }
            $model->setAttributes($_POST['Users']);
            $profile = $profile->setProfile($_POST['Profiles']);
            $valid = $model->validate();
            $valid = $profile->validate() && $valid;
            if ($valid) {
                $transaction = $model->getDbConnection()->beginTransaction();
                try {
                    if ($model->save()) {
                        $model->editProfile($_POST['Profiles']);
                       // $model->addRestaurantForAdmin();
                        $transaction->commit();
                        $this->redirect(array('admin'));
                    }
                } catch (Exception $e) {
                    $transaction->rollback();
                    throw $e;
                }
            }
        }


        $this->render('update', array(
            'model' => $model,
            'profile' => $profile,
            'selected' => $selected
        ));
    }

    public function actionDelete($id) {
        if (Yii::app()->getRequest()->getIsPostRequest()) {
            //Yii::log("testing", CLogger::LEVEL_WARNING, $this->loadModel($id, 'Users'));
//            Profiles::model()->deleteAll('user_id=:user_id', array(':user_id' => $id));
//            UserHasRole::model()->deleteAll('user_id=:user_id', array(':user_id' => $id));
//            UserPreferences::model()->deleteAll('user_id=:user_id', array(':user_id' => $id));
//            AuthKey::model()->deleteAll('user_id=:user_id', array(':user_id' => $id));
//            UserFavoriteRestaurant::model()->deleteAll('user_id=:user_id', array(':user_id' => $id));
//            Review::model()->deleteAll('reviewed_by=:reviewed_by', array(':reviewed_by' => $id));


            $this->loadModel($id, 'Users')->delete();

            if (!Yii::app()->getRequest()->getIsAjaxRequest())
                $this->redirect(array('admin'));
        }
        else
            throw new CHttpException(400, Yii::t('app', 'Your request is invalid.'));
    }

    public function actionIndex() {
        $dataProvider = new CActiveDataProvider('Users');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    public function actionAdmin() {

        $model = new Users('search');

        $model->unsetAttributes();

        if (isset($_GET['Users']))
            $model->setAttributes($_GET['Users']);

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    

    public function actionPassword($id) {

        $model = Users::model()->find('id=:id', array(':id' => $id));
        if (is_array($model->profiles)) {
            $profile = ($model->profiles[0]);
        } else {
            $profile = $model->profiles;
        }

        // $restaurantId = $_POST['restaurant_id'];

        changePassword($model, $_POST['password']);
        try {
            if (Yii::app()->user->isAdmin()) {
                if ($profile->email) {
                    $name = $profile->firstname . $profile->lastname;
                    //  emailSend($name, $profile->email, $_POST['password']);
                }
            }
        } catch (Exception $exc) {
            
        }

        yii::app()->user->setFlash('RestAdminSucMsg', Message::MSG_REST_SUCCESS_CNGPASSWORD);
        if (Yii::app()->user->isAdmin()) {
            $this->redirect(array('update', 'id' => $id));
        } else {
            $this->redirect(array('profile'));
        }
    }

    public function actionProfile() {

        $session = new CHttpSession;

        $model = $this->loadModel(Yii::app()->user->id, 'Users');
        $dbUsername = $model->username;
        if (is_array($model->profiles)) {
            $profile = ($model->profiles[0]);
        } else {
            $profile = $model->profiles;
        }


        $selected = array();
        if (isset($_POST['Profiles'])) {

            $model->setAttributes($_POST['Users']);
            if (isset($_POST['Users']['restaurantAdmins'])) {
                $selected = $_POST['Users']['restaurantAdmins'];
            }
            $profile->setProfile($_POST['Profiles']);
            $valid = $model->validate();
            $valid = $profile->validate() && $valid;
            if ($valid) {
                $transaction = $model->getDbConnection()->beginTransaction();
                try {
                    $model->save(false);
                    $model->editProfile();
                    $transaction->commit();
                    yii::app()->user->setFlash('ProfileSucMsg', Message::MSG_PROFILE_SUCCESS_MSG);
                    if ($dbUsername != $model->username) {

                        $this->redirect(array('user/user/logout'));
                    }
                    $this->redirect(array('profile'));
                } catch (Exception $ex) {
                    $transaction->rollback();
                    throw $e;
                }
            }
        }

        $this->render('update', array(
            'model' => $model,
            'profile' => $profile,
            'selected' => $selected
        ));
    }

}